import { ValidatorResult } from 'jsonschema';
import { useEffect, useMemo, useState } from 'react';
import { FC, PropsWithChildren } from 'react';
import { vailidatePlankProps } from '..';
import { IPlankProps } from '../types/IPlankProps';

const error = console.error.bind(null, '[PlankPropsValidate]');

export const PlankPropsValidate: FC<
  PropsWithChildren<{
    plankProps?: IPlankProps;
    onValidate?: (isValid: boolean) => void;
  }>
> = (props) => {
  const { plankProps } = props;
  const validateResult = useMemo<ValidatorResult | null>(() => {
    if (!plankProps) return null;
    return vailidatePlankProps(plankProps);
  }, [plankProps]);

  useEffect(() => {
    if (!validateResult) return;

    const isValid = validateResult?.valid;

    props.onValidate?.(isValid);

    if (!isValid) {
      error('Props Error:', validateResult);
    }
  }, [validateResult]);

  if (validateResult && !validateResult.valid) {
    return (
      <>
        输入参数有误:
        <pre>{JSON.stringify(validateResult.errors, null, 4)}</pre>
      </>
    );
  } else {
    return <>{props.children}</>;
  }
};
